package com.ruoyi.web.shopping.service.impl;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.web.shopping.entity.Person;
import com.ruoyi.web.shopping.mapper.CaptchasMapper;
import com.ruoyi.web.shopping.mapper.PersonMapper;
import com.ruoyi.web.shopping.service.CaptchasService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CaptchaServiceImpl implements CaptchasService {

    @Autowired
    private CaptchasMapper captchaMapper;

    @Autowired
    private PersonMapper personMapper;

    @Autowired
    private RedisTemplate redisTemplate;

//    public Captcha getById(String id) {
//        Captcha captcha = captchaMapper.getById(id);
//        return captcha;
//    }

    /**
     * 随机获取模板
     *
     * @return
     */
    @Override
    public String getAllTemeplate() {
        List<String> captcha = captchaMapper.getAllTemeplate();
        int size = captcha.size();
        Random random = new Random();
        int i = random.nextInt(size);
        String s = captcha.get(i);
        return s;
    }

    /**
     * 根据用户id、模板id以及答案进行验证码登录
     *
     * @param userid
     * @param templateid
     * @param result
     * @return
     */
    @Override
    public String selectByTemplateId(String userid, String templateid, String result) {
        String id = personMapper.getById(userid);
        if (id != null && userid.equals(id)){
            String result1 = captchaMapper.selectByTemplateId(templateid);
            if (result1.equals(result)) {
                redisTemplate.opsForValue().set(userid, result, 5, TimeUnit.MINUTES);
                return "验证码正确！";
            }
            return "验证码错误！";
        }else {
            personMapper.setPersonId(userid);
            return "用户注册完成！";
        }

//        String result1 = captchaMapper.selectByTemplateId(templateid);
//        if (result1.equals(result)) {
//            redisTemplate.opsForValue().set(userid, result, 5, TimeUnit.MINUTES);
//            return "验证码正确！";
//        }
//        return "验证码错误！";
    }

    /**
     * 根据用户id判断验证码是否过期
     *
     * @param userid
     * @return
     */
    @Override
    public String getUserid(String userid) {
        Object codeInSession = redisTemplate.opsForValue().get(userid);
        if (codeInSession != null && codeInSession.equals(codeInSession)) {
            return "登录成功";
        }
        return "登录失败";
    }
}
